package com.example.mqttxconsumer.controller;

import com.example.mqttxconsumer.config.MqttxProviderConfig;
import com.example.mqttxconsumer.vo.PumpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class ProviderController {
    @Resource
    private MqttxProviderConfig mqttxProviderConfig;

    @RequestMapping("/control")
    public String sendMessage(@RequestParam(value = "message")String message){
        ObjectMapper objectMapper = new ObjectMapper();
        try{
            PumpStatus pumpStatus = new PumpStatus();
            pumpStatus.setMsg(message);

            String json = objectMapper.writeValueAsString(pumpStatus);

            mqttxProviderConfig.publish(0,true,"home/greenhouse/control",json);
            return "send success";
        }catch (MqttException e){
            e.printStackTrace();
            return "send fail";
        }catch (Exception e){
            return "send fail";
        }
    }
}
